package com.zzh.partnersys.controller;

import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.entity.UserDO;
import com.zzh.partnersys.service.UserService;
import com.zzh.partnersys.utils.GeoUtils;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.*;

import static com.zzh.partnersys.constant.UserConstant.USER_CACHE_LOCATION_KEY;

/**
 * 获取Geo定位信息
 * @author zzh
 */
@RestController
@RequestMapping("/geo")
public class GeoTestController {


    @Autowired
    private GeoUtils geoUtils;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 获取IP地址对应的经纬度信息
     * @param request
     * @return
     */
    @GetMapping("/test")
    public ResultUtils testGeoInfo(HttpServletRequest request) {
        return ResultUtils.ok(request.getRemoteAddr());
    }

    /**
     * 获取IP地址对应的经纬度信息
     * @param request
     * @return
     */
    @GetMapping("/getGeoInfoByIP")
    public ResultUtils getGeoInfoByIP(HttpServletRequest request) {
        String remoteAddr = "120.197.59.5";
//        String remoteAddr = request.getRemoteAddr();
        String currentIPGeoInfo = geoUtils.getCurrentIPGeoInfo(remoteAddr);
        HashMap<String, String> map = new HashMap<>();
        if (currentIPGeoInfo!=null){
            String[] split = currentIPGeoInfo.split(",");
            String address = geoUtils.getAddress(split[0], split[1]);
            map.put("address", address);
        }
        map.put("lngAndLat", currentIPGeoInfo);
        return ResultUtils.ok(map);
    }


    /**
     * 根据id搜索附近的用户信�?
     */
    @GetMapping("/getNearbyUsers")
    public ResultUtils getNearbyUsers(HttpServletRequest request) {
        UserDO currentUserDO = userService.getCurrentUser(request);
        Long id = currentUserDO.getId();
//        RGeo<String> findFriendGeo = redissonClient.getGeo(USER_CACHE_LOCATION_KEY);
//        boolean exist = findFriendGeo.pos(String.valueOf(id)) != null;

        GeoOperations<String, Object> stringObjectGeoOperations = redisTemplate.opsForGeo();
        boolean exist  = Objects.requireNonNull(stringObjectGeoOperations.position(USER_CACHE_LOCATION_KEY, String.valueOf(id))).isEmpty();
        if(exist){//如果不存在，则添加到redis�?
            String remoteAddr = "120.197.59.5";
//            String remoteAddr = request.getRemoteAddr();
            String currentIPGeoInfo = geoUtils.getCurrentIPGeoInfo(remoteAddr);
            if (currentIPGeoInfo == null){
                System.out.println("获取当前IP地址的经纬度信息失败");
            }
            String[] split = currentIPGeoInfo.split(",");
            double lng = Double.parseDouble(split[0]);
            double lat = Double.parseDouble(split[1]);
//            findFriendGeo.add(new GeoEntry(lng, lat, String.valueOf(id)));
            redisTemplate.opsForGeo().add(USER_CACHE_LOCATION_KEY, new Point(lng, lat), String.valueOf(id));
        }
        //查询附近的用户信�?1km以内
//        List<String> userIdList = findFriendGeo.radius(String.valueOf(id), 1, GeoUnit.KILOMETERS);
//        System.out.println(userIdList);
        List<Long> longUserIdList = new ArrayList<>();

        GeoResults<RedisGeoCommands.GeoLocation<Object>> resultsByMember = redisTemplate.opsForGeo().radius("findFriend", "10", new Distance(1, RedisGeoCommands.DistanceUnit.KILOMETERS));
        for (GeoResult<RedisGeoCommands.GeoLocation<Object>> result : resultsByMember) {
            System.out.println(result.getContent().getName());
            longUserIdList.add(Long.parseLong((String) result.getContent().getName()));
        }

        if (longUserIdList == null || longUserIdList.isEmpty()){
            return ResultUtils.ok(null);
        }
//        // 根据id获取用户信息
//        List<Long> longUserIdList = userIdList.stream()
//                .map(Long::parseLong).filter(userId -> !userId.equals(id))
//                .collect(Collectors.toList());
        // 根据id获取用户信息
        List<UserDO> userDOS = userService.selectUsersByIds(longUserIdList);
        return ResultUtils.ok(userDOS);
    }



}
